package owg.util;

import java.awt.Rectangle;

import owg.shallowserializer.GenericArrayParser;
import owg.shallowserializer.ShallowSerializer;
import owg.shallowserializer.TypeParser;
import owg.shallowserializer.ShallowSerializer.ToString;
import owg.util.data.property.Property;

public class AdditionalParsers
{	
	private static boolean isRegistered = false;
	public static void register()
	{
		if(!isRegistered)
			isRegistered = true;
		ShallowSerializer.registerInternalSerializer(Rectangle.class, (Rectangle r) -> {return ""+r.x+','+r.y+','+r.width+','+r.height;});
		ShallowSerializer.registerInternalParser(Rectangle.class, new TypeParser.Parser<Rectangle>() {
			GenericArrayParser<Integer> iArrayParser = new GenericArrayParser<>(Integer.class, TypeParser.intParser, 4);
			@Override
			public Rectangle parse(Class<Rectangle> type, String str, Rectangle def) throws Exception
			{
				if(str.trim().equals("null"))
					return null;
				Integer[] a = iArrayParser.parse(Integer[].class, str, null);
				return new Rectangle(a[0],a[1],a[2],a[3]);
			}
		});
		
		@SuppressWarnings("rawtypes")
		ToString<Property> propertySerializer = new ToString<Property>() {
		    @Override
		    public String toString(Property p) {
		        return p.getType().getName()+":"+ShallowSerializer.toString(p.getType(), p.get());
		    }
		};
		ShallowSerializer.registerInternalSerializer(Property.class, propertySerializer);
		@SuppressWarnings({ "unchecked", "rawtypes" })
		TypeParser.Parser<Property> propertyParser = new TypeParser.Parser<Property>() {
		    
		    @Override
		    public Property parse(Class<Property> type, String str, Property def) throws Exception {
			int colonPos = str.indexOf(':');
			if(colonPos == -1)
			    throw new IllegalArgumentException(str+" is not a property because it has no colon...");
			String className = str.substring(0, colonPos).trim();
			Class<?> internalType = Class.forName(className);
			if(def != null && def.getType() != internalType)
			    throw new IllegalArgumentException("Class name in serialized file was: "+internalType+" but default class name is: "+def.getType());
			String valueStr = str.substring(colonPos+1).trim();
			Object internalValue = TypeParser.parse(internalType, valueStr);
			return new Property(internalType, internalValue);
		    }
		};
		ShallowSerializer.registerInternalParser(Property.class, propertyParser);
	    }
	}
